package com.ayit.controller;


import com.auth0.jwt.JWT;
import com.ayit.pojo.Result;
import com.ayit.pojo.User;
import com.ayit.service.UserService;
import com.ayit.utils.JwtUtil;
import com.ayit.utils.Md5Util;
import com.ayit.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated//参数校验的依赖
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
        //根据用户注册时输入的用户名去数据库中查询用户
            User u = userService.findByName(username);
            if(u == null){
                //没有占用，开始注册
                userService.register(username,password);
                return Result.success();
            }else{
                //有占用
                return Result.error("用户名已被占用！");
            }
    }


    //用户登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$")String password){
        //根据用户名查询用户
        User loginUser = userService.findByName(username);
        //判断用户是否存在
        if(loginUser == null){
            return Result.error("用户名错误！");
        }
        //判断密码是否正确 此时loginUser对应的密码是MD5加密的密文
        // 先加密再比较
        //输入的password  和  查询到数据库中的username的password  比较
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){//登录成功
            //在这里，lombok的data注解生成的equal方法已经重写了Object类中的方法，比较两者的字符串是否一致，返回值是boolean
            Map<String,Object> claims = new HashMap<>();//创建Map类型的对象用于封装用户数据
            //claims指jwt中载荷的json数据，因为可以有多个载荷，所以用map来存取
            //生成Jwt令牌
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            //把Token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            //返回Jwt令牌
            return Result.success(token);
        }
        return Result.error("密码错误！");
    }

    //获取用户详细信息
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/){
        //根据用户名查询用户
       /* Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");*/
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByName(username);
        return Result.success(user);
    }


    //更新用户基本信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success("OK!");
    }


    //更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success("用户头像更新成功！");
    }


    //更新用户密码
    @PatchMapping("/updatePwd")//添加@RequestBody才能自动读取请求体中的JSON格式的数据并转换成对象
    public Result updatePwd(@RequestBody Map<String,String> params, @RequestHeader("Authorization") String token){
        //1.校验参数
        String oldPwd =  params.get("old_pwd");
        String newPwd =  params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要参数！");
        }

        //原密码是否正确
        //调用Service层拿到原密码，再和oldPwd比对
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByName(username);
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return  Result.error("原密码填写不正确！");
        }
        //对newPwd进行参数校验*
        if(!newPwd.matches(("^\\S{5,16}$"))){
            return Result.error("您设置的新密码长度应∈[5,16]！");
        }
        //oldPwd和newPwd是否一样*
        if(oldPwd.equals(newPwd)){
            return Result.error("你的新密码与老密码一致，你想干啥？");
        }
        //newPwd和rePwd是否一样
        if(!rePwd.equals(newPwd)){
            return Result.error("两次填写的新密码不一样！");
        }
        //调用Service完成密码更新
        userService.updatePwd(newPwd);
        //删除redis中对应的token
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        //响应数据
        return Result.success("更新密码成功！");
    }
}
